package com.xiguaji.tiktok.utils.guojipay;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class GuoJiPayUtil {



    public static String sign(CreateOrderRequest c) throws UnsupportedEncodingException {
        Map<String,Object> params = new HashMap<>();
        params.put("ProductId",c.getProductId());
        params.put("OrderNo", c.getOrderNo());
        params.put("Name", c.getName());
        params.put("TotalFee", c.getTotalFee());
        params.put("PayType", c.getPayType());
        params.put("ClientIP", c.getClientIP());
        params.put("Content", c.getContent());
        params.put("Remarks", c.getRemarks());
        params.put("SignKey","71053DE5C4284E8183A2A3A09E627B65");
        return DigestUtils.md5Hex(createSign(params,false));
    }


    /**
     * 构造签名
     * @param params
     * @param encode
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String createSign(Map<String, Object> params, boolean encode) throws UnsupportedEncodingException {
        Set<String> keysSet = params.keySet();
        Object[] keys = keysSet.toArray();
        Arrays.sort(keys);
        StringBuffer temp = new StringBuffer();
        boolean first = true;
        for (Object key : keys) {
            Object value = params.get(key);
            if(StringUtils.isEmpty(value)){
                continue;
            }

            if (first) {
                first = false;
            } else {
                temp.append("&");
            }
            temp.append(key).append("=");
            String valueString = "";
            if (null != value) {
                valueString = value.toString();
            }
            if (encode) {
                temp.append(URLEncoder.encode(valueString, "UTF-8"));
            } else {
                temp.append(valueString);
            }
        }
        return temp.toString();
    }
}
